package com.wzy.common.base.Youdao;

/**
 * 2 * @Author: wuzhengyu
 * 3 * @Date: 2021/4/23 18:06
 * 4
 */

import com.wzy.common.base.util.JacksonUtil;

import javax.websocket.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@ClientEndpoint
public class Websocket {
    public static ArrayList<Map<String, String>> caption = new ArrayList<>();
    private void print(Object obj) {
        System.out.println(obj.toString());
    }

    private void toCaption(String obj) {
        Map<String, Object> map = JacksonUtil.string2Map(obj);
        //{"result":{"transPattern":"stream","segId":1,"bg":1080,"context":"More than","from":"en","tranContent":"超过","to":"zh-CHS","partial":true,"ed":1560},"RequestId":"f77ee5ad-b637-4077-ba25-a28c6c7369f8","errorCode":"0","action":"recognition"}123
        assert map != null;

        Map<String, Object> result = (Map<String, Object>) map.get("result");
        if (result.size() == 0) {
            return;
        }
        String segId = result.get("segId").toString();
        String context = (String) result.get("context");
        String tranContent = (String) result.get("tranContent");
        String bg = (String) result.get("bg").toString();
        String ed = (String) result.get("ed").toString();
        Map<String, String> captionMap = new HashMap<String, String>(){{
            put("segId", segId);
            put("context", context);
            put("tranContent", tranContent);
            put("bg", bg);
            put("ed", ed);
        }};
        if (caption.size() < Integer.parseInt(segId)) {
            caption.add(captionMap);
        } else {
            caption.set(Integer.parseInt(segId) - 1, captionMap);
        }

        //System.out.println(caption);
    }

    Session session;

    @OnOpen
    public void onOpen(Session session) {
        print("Connect to endpoint: " + session.getBasicRemote());
        this.session = session;
    }

    @OnMessage
    public void onMessage(String message) throws IOException {
        print(message);
        toCaption(message);
        if (message.contains("\"errorCode\":\"304\"")) {
            onClose();
        }

    }

    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    @OnClose
    public void onClose() throws IOException {
        if(this.session.isOpen()){
            this.session.close();
        }
        print("session close");
        //System.exit(0);
    }

}